package com.quartz.tasks.web.controller;

import com.quartz.tasks.web.entity.QuartzEntity;
import com.quartz.tasks.web.service.TaskService;
import com.quartz.tasks.web.vo.Result;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * @author 彭长云
 * @Description:任务操作
 * @date 2018/12/5 15:39
 */
@RestController
@RequestMapping("/job")
public class TaskController extends BaseController{

    @Value("${task.execute.class}")
    private String executeClass;
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private TaskService jobService;

    @PostMapping("/add")
    public Result save(@RequestBody @Valid QuartzEntity quartz){
        logger.info("新增任务");
        try {
            //如果是修改  展示旧的 任务
            if(quartz.getOldJobGroup()!=null){
                JobKey key = new JobKey(quartz.getOldJobName(),quartz.getOldJobGroup());
                scheduler.deleteJob(key);
            }
            Class cls = Class.forName(executeClass) ;
            cls.newInstance();
            //构建job信息
            JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
                    quartz.getJobGroup())
                    .withDescription(quartz.getDescription()).build();
            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+quartz.getJobName(), quartz.getJobGroup())
                    .startNow().withSchedule(cronScheduleBuilder).build();
            trigger.getJobDataMap().put("url",quartz.getUrl());
            trigger.getJobDataMap().put("jsonData",quartz.getJsonData());

            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);
        } catch (Exception e) {
            e.printStackTrace();
            return error();
        }
        return success();
    }
    @RequestMapping("/list")
    public Result list(@RequestBody  QuartzEntity quartz,Integer pageNo,Integer pageSize){
        logger.info("任务列表");
        List<QuartzEntity> list = jobService.listQuartzEntity(quartz, pageNo, pageSize);
        return success(list);
    }
    @PostMapping("/trigger")
    public  Result trigger(@RequestBody QuartzEntity quartz,HttpServletResponse response) {
        logger.info("触发任务");
        try {
            JobKey key = new JobKey(quartz.getJobName(),quartz.getJobGroup());
            scheduler.triggerJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return error();
        }
        return success();
    }
    @PostMapping("/pause")
    public  Result pause(@RequestBody QuartzEntity quartz,HttpServletResponse response) {
        logger.info("停止任务-{},{}",quartz.getJobGroup(),quartz.getJobName());
        try {
            JobKey key = new JobKey(quartz.getJobName(),quartz.getJobGroup());
            scheduler.pauseJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return error();
        }
        return success();
    }
    @PostMapping("/resume")
    public  Result resume(@RequestBody  QuartzEntity quartz,HttpServletResponse response) {
        logger.info("恢复任务-{},{}",quartz.getJobGroup(),quartz.getJobName());
        try {
            JobKey key = new JobKey(quartz.getJobName(),quartz.getJobGroup());
            scheduler.resumeJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return error();
        }
        return success();
    }
    @PostMapping("/remove")
    public  Result remove(@RequestBody QuartzEntity quartz, HttpServletResponse response) {
        logger.info("移除任务-{},{}",quartz.getJobGroup(),quartz.getJobName());
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartz.getJobName(), quartz.getJobGroup());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(quartz.getJobName(), quartz.getJobGroup()));
        } catch (Exception e) {
            e.printStackTrace();
            return error();
        }
        return success();
    }
}
